# !/usr/bin/python
# -*- coding: UTF-8 -*-
from optparse import OptionParser
from printLog import printLog
import jsonFileUtils
import deleteUnusedMetaFile
import os
import shutil
import beforeBuildUtils
# /////////////////////////////////////////////////////////////// 构建 //////////////////////////////////////////////////////////////////
# COCOS引擎目录
enginePath = '/Applications/CocosCreator.app/Contents/MacOS'
# COCOS打包命令
COCOS_BUILD_CMD = '/Applications/CocosCreator.app/Contents/MacOS/CocosCreator --path {0} --build \"{1}\"'
# COCOS编译命令
COCOS_COMPILE_CMD = '/Applications/CocosCreator.app/Contents/MacOS/CocosCreator --path {0} --compile \"{1}\"'
# natve打包参数
BUILD_PARAM = 'platform=ios;debug=false;optimizeHotUpdate=false;inlineSpriteFrames=false;mergeStartScene=true;template=link;\
xxteaKey=1449bb9d-2f98-4f;zipCompressJs=true;encryptJs=false;md5Cache=false;debug=false;'

# H5打包参数
BUILD_PARAM_H5 = 'platform=web-mobile;debug=false;optimizeHotUpdate=false;inlineSpriteFrames=true;mergeStartScene=false;template=web-mobile;webOrientation=landscape;\
xxteaKey=1449bb9d-2f98-4f;zipCompressJs=true;encryptJs=false;md5Cache=false;debug=false'

# cocos BUILDER
COCOS_BUILDER_PATH = 'settings/builder.json'
# 启动场景UUID
START_SCENE_UUID = '5dffaf13-b2fe-4cde-aa78-dbe84c726374'


def getBuildCMD(workSpace, buildParam):
    return COCOS_BUILD_CMD.format(workSpace, buildParam)


def addBuildParam(buildParam, param):
    buildParam += ';' + param
    return buildParam


# 执行平台CMD命令
def excuteCmd(cmdStr):
    os.system(cmdStr)


def updateStartSceneUuid():
    printLog("-------------设置启动场景uuid开始---------------")
    data = jsonFileUtils.getJsonDataFromFile(COCOS_BUILDER_PATH)
    data['startScene'] = START_SCENE_UUID
    jsonFileUtils.saveJsonDataToFile(COCOS_BUILDER_PATH, data)
    printLog("-------------设置启动场景uuid完成---------------")


def setDebugCompileParam():
    netType = os.environ['NETTYPE']
    printLog("-------------设置启动场景uuid完成---------11111111-----netType-")
    printLog(netType)
    global BUILD_PARAM
    BUILD_PARAM = BUILD_PARAM.replace('debug=false', 'debug=true')
    if netType == 'innertest' :
        #global BUILD_PARAM
        printLog("-------------设置启动场景uuid完成---------11111111-----innertest-")
        BUILD_PARAM = BUILD_PARAM.replace('debug=false', 'debug=true')
        print('inner_test_param =', BUILD_PARAM)
    if netType == 'online' :
        #global BUILD_PARAM
        printLog("-------------设置启动场景uuid完成---------11111111-----online-")
        BUILD_PARAM = BUILD_PARAM.replace('encryptJs=false','encryptJs=true')
        BUILD_PARAM = BUILD_PARAM.replace('debug=true', 'debug=false')
        print('online_param =', BUILD_PARAM)


def getIosBuildParam(workSpace):
    buildParam = BUILD_PARAM
    return buildParam


def buildIos(workSpace):
    printLog("---------构建资源开始------------")
    deleteUnusedMetaFile.run()
    setDebugCompileParam()
    buildParam = getIosBuildParam(workSpace)
    cwd = os.getcwd()
    beforeBuildUtils.deleteBack()
    # printLog(cwd)
    # 切换到引擎目录打包
    os.chdir(enginePath)
    # 开始执行构建命令
    cmdBuild = getBuildCMD(workSpace, buildParam)
    printLog("---------构建资源配置：" + cmdBuild)
    excuteCmd(cmdBuild)
    # 切回到工作目录
    os.chdir(cwd)
    printLog("---------构建资源完成------------")

def buildH5(workSpace):
    printLog("---------构建资源开始------------")
    deleteUnusedMetaFile.run()
    setDebugCompileParam()
    buildParam = BUILD_PARAM_H5
    cwd = os.getcwd()
    # printLog(cwd)
    # 切换到引擎目录打包
    os.chdir(enginePath)
    # 开始执行构建命令
    cmdBuild = getBuildCMD(workSpace, buildParam)
    printLog("---------构建资源配置：" + cmdBuild)
    excuteCmd(cmdBuild)
    # 切回到工作目录
    os.chdir(cwd)
    printLog("---------构建H5完成------------")

if __name__ == "__main__":
    parser = OptionParser()
    parser.add_option(
        '-e',
        '--enginePath',
        dest="enginePath",
        default='/Applications/CocosCreator.app/Contents/MacOS')
    parser.add_option('-w', '--workSpace', dest="workSpace", default='../')
    (option, args) = parser.parse_args()
    enginePath = option.enginePath
    workSpace = os.path.abspath(os.path.join(os.getcwd(), option.workSpace))
    printLog("-------------引擎目录-----------" + enginePath)
    printLog("-------------工作目录-----------" + workSpace)
    os.chdir(workSpace)
    beforeBuildUtils.autoMakeGitBranchs(workSpace)
    updateStartSceneUuid()
    webflag = os.environ['web']
    printLog("-------------webflag-----------" + webflag)
    if webflag == 'web':
        buildH5(workSpace)
    else:
        buildIos(workSpace)